package org.sdkj.device.test.vein.utils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.sdkj.device.tg.jni.TGComApi860Jni;
import org.sdkj.device.tg.jni.TGFingerVeinApiJni;

public class VeinUtils {
	public static final int FEATURE_LENGTH = 5776;
	public static final int FEATURE_MAX_LENGTH = FEATURE_LENGTH * 3;

	/**
	 * 获取特征（feature：特征，encryptData，加密图片）
	 * 
	 * @param jpegData
	 * @return
	 */
	public static Map<String, Object> img2Feature(byte[] jpegData) {
		String license = "c:/license.dat";
		byte[] feature = new byte[FEATURE_LENGTH];

		byte[] encryptData = new byte[320 * 240];// 为防止以后修改高宽，定义一个图像最大值，然后通过XG_DecodeVeinBmp输出参数widthheigth，确定当前图片最大值。刘工建议。2017.11.17。
		int[] width,height;
		if(jpegData.length==320*140)
		{
			width = new int[]{320};
			height = new int[]{140};
			encryptData = jpegData;
		}else
		{
			width = new int[]{1};
			height = new int[]{1};
			TGComApi860Jni.API.TG_DecodeVeinBmp(jpegData, jpegData.length, encryptData, width, height, null, null);
			Arrays.copyOfRange(encryptData, 0, width[0] * height[0]);
		}
		 
		

		int tgImgExtractFeature = TGFingerVeinApiJni.API.TGImgExtractFeature(encryptData, width[0], height[0], feature,
				license);
		if (tgImgExtractFeature == 1) {
			throw new RuntimeException("lincese过期！");
		}
		if (tgImgExtractFeature == 2) {
			throw new RuntimeException("lincese无效！");
		}
		if (tgImgExtractFeature == 3) {
			throw new RuntimeException("图像质量差！");
		}
		if (tgImgExtractFeature != 0) {
			throw new RuntimeException("提取特征失败！");
		}

		Map<String, Object> map = new HashMap<>();
		map.put("feature", feature);
		map.put("width", width[0]);
		map.put("height", height[0]);
		map.put("encryptData", encryptData);
		return map;
	}

	public static byte[] toBigFeatrue(byte[] feature1, byte[] feature2, byte[] feature3) {
		byte[] fusionFeature = new byte[FEATURE_MAX_LENGTH];
		int tgFusionFeature = TGFingerVeinApiJni.API.TGFusionFeature(feature1, feature2, feature3, fusionFeature);
		if (tgFusionFeature != 0) {
			throw new RuntimeException("融合特征失败！");
		}
		return fusionFeature;
	}

	public static int search1_N(byte[] recvBuf, List<byte[]> templates) {
		int templateSize = FEATURE_MAX_LENGTH * templates.size();
		byte[] templateLib = new byte[templateSize];
		{
			for (int i = 0; i < templates.size(); i++) {
				byte[] feature = templates.get(i);
				if (feature.length != (FEATURE_MAX_LENGTH)) {
					throw new RuntimeException("特征长度非法：" + i + ":" + feature.length);
				}
				System.arraycopy(feature, 0, templateLib, FEATURE_MAX_LENGTH * i, feature.length);
			}
		}
		int[] matchIndex = new int[1];
		byte[] updateRegFeature = new byte[FEATURE_MAX_LENGTH];// 验证后计算出的优化后的模板，可以用来替换之前的模板
		int tgMatchFeature = TGFingerVeinApiJni.API.TGMatchFeature1N(recvBuf, templateLib,
				templateLib.length / (FEATURE_MAX_LENGTH), matchIndex, updateRegFeature);
		if (tgMatchFeature != 0) {
			return -1;
		} else {
			return matchIndex[0];
		}
	}
}
